package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import model.User;

import view.SelectUserPanel;
import view.templates.MyJButton;

public class SelectUserListener implements ListSelectionListener,
		ActionListener {

	private Controller controller = null;
	private SelectUserPanel selectUser = null;

	public SelectUserListener(Controller controller) {
		this.controller = controller;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		this.selectUser = controller.getFrame().getSelectUser();

		if (e.getSource().getClass() == MyJButton.class) {
			MyJButton b = (MyJButton) e.getSource();
			if (b == selectUser.getNewUserButton()) {
				System.err.println("Neuer Benutzer Button angeklickt!");
			} else if (b == selectUser.getOkayButton()) {
				if (selectUser.askForPassword()) {
					controller.setCurrentUser(controller.getFrame()
							.getSelectUser().getUserList().getSelectedValue());
					controller.getFrame().initHomeScreen();
				}
			} else if (b == selectUser.getAdminViewPanel()) {
				// TODO Sicherheitsabfrage
				controller.getFrame().initAdminScreen();
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void valueChanged(ListSelectionEvent e) {
		this.selectUser = controller.getFrame().getSelectUser();

		if (e.getSource().getClass() == JList.class) {
			JList<User> userList = (JList<User>) e.getSource();
			// Okay Button aktivieren/deaktivieren
			if (!e.getValueIsAdjusting() && userList.getSelectedIndex() != -1) {
				selectUser.getOkayButton().setEnabled(true);
			}
			if (!e.getValueIsAdjusting() && userList.getSelectedIndex() == -1) {
				selectUser.getOkayButton().setEnabled(false);
			}
		}
	}
}
